<template>
  <el-dialog
    v-el-drag-dialog
    title="查看历史记录"
    :visible.sync="dialogVisible"
    append-to-body
    fullscreen
    @close="dialogClose"
  >
    <el-form ref="searchForm" :inline="true" :model="params" class="ele-form-search">
      <el-form-item>
        <el-date-picker
          v-model="params.created_at"
          type="daterange"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item>
        <el-input v-model="params.per" type="number" placeholder="间隔时间">
          <template slot="append">分钟</template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="ele-btn-icon" icon="el-icon-search" type="primary" @click="search">查询</el-button>
        <el-button class="ele-btn-icon" icon="el-icon-download" type="success" @click="exportExcel">下载数据</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      border
    >
      <el-table-column
        v-for="(item,index) in rtuPortDisplays"
        :key="index"
        :prop="item.namekey"
        :label="item.name"
        align="center"
      />
    </el-table>
  </el-dialog>
</template>

<script>
import { getHistories } from '@/api/statistics'
import { removeEmptyField, getCurrentDate, getNextDate } from '@/utils'
import qs from 'qs'
export default {
  data() {
    return {
      dialogVisible: false,
      params: { created_at: [getNextDate(getCurrentDate(), -1), getCurrentDate()], per: 30 },
      tableData: [],
      rtuPortDisplays: [],
      loading: true
    }
  },
  methods: {
    show(device) {
      const rtuPortDisplays = device.rtuPortDisplays.filter((val) => {
        return val.identity.indexOf('census') > -1
      }).map((val) => {
        return {
          namekey: val.namekey,
          name: val.name
        }
      })
      rtuPortDisplays.unshift({ name: '时间', namekey: 'time' })
      this.rtuPortDisplays = rtuPortDisplays
      this.params = Object.assign(this.params, { serialno: device.serialno })
      this.dialogVisible = true
      this.getHistories()
    },
    search() {
      this.tableData = []
      this.getHistories()
    },
    exportExcel() {
      window.open(`https://www.zesi.com.cn/api/export/history?${qs.stringify(this.params)}`)
    },
    dialogClose() {
      this.tableData = []
    },
    async getHistories() {
      this.loading = true
      const { data } = await getHistories(removeEmptyField(this.params)).catch(() => {
        this.loading = false
      })
      this.tableData = data.datas
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
